package crawler.ford;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zql.entity.AgencyEntity;

import util.HttpConnectionGet;
import util.Location;
import util.MybatisTool;
import util.TianYanCha;

public class ChangAnFuTe {
	List<AgencyEntity> getAgency() {
		List<AgencyEntity> list = new ArrayList<AgencyEntity>();
		List<String> dealerNames = new ArrayList<String>();
		String getPro = "https://www.ford.com.cn/content/ford/cn/zh_cn/configuration/application-and-services-config/provinceCityDropDowns.multiFieldDropdown.data";
		String proStr = HttpConnectionGet.getJson(getPro);
		JSONArray provinces = JSON.parseArray(proStr);
		for (int i = 0; i < provinces.size(); i++) {
			JSONObject pro = provinces.getJSONObject(i);
			String proName = pro.getString("provinceKey");
			JSONArray citys = pro.getJSONArray("cityList");
			for (int j = 0; j < citys.size(); j++) {
				JSONObject city = citys.getJSONObject(j);
				String cityName = city.getString("cityKey");

				String getLocation = "https://restapi.amap.com/v3/geocode/geo?key=1891d0f847c0a210a88015fdd4c3bc46&s=rsv3&address="
						+ proName + cityName;
				String locationStr = HttpConnectionGet.getJson(getLocation);
				JSONObject location = JSON.parseObject(locationStr);
				String status = location.getString("status");
				if ("1".equals(status)) {
					JSONArray geocodes = location.getJSONArray("geocodes");
					String lngAndLat = geocodes.getJSONObject(0).getString("location");

					String getDealer = "https://yuntuapi.amap.com/datasearch/local?s=rsv3&key=1891d0f847c0a210a88015fdd4c3bc46&extensions=all&language=en&enc=utf-8&output=jsonp&&sortrule=_distance:1&autoFitView=true&panel=result&keywords=&limit=100&sortrule=_id:1&tableid=55adb0c7e4b0a76fce4c8dd6&platform=JS&logversion=2.0&sdkversion=1.4.2&appname=http://www.ford.com.cn/dealer/locator?intcmp=hp-return-fd&csid=6F094767-5285-454B-BC73-0D18F9C7223B&center="
							+ lngAndLat + "&city=" + cityName + "&filter=AdministrativeArea:" + proName
							+ "&_=1520996356088";
					String dealerStr = HttpConnectionGet.getJson(getDealer);
					JSONObject dealerJSON = JSON.parseObject(dealerStr);
					JSONArray dealers = dealerJSON.getJSONArray("datas");
					for (int k = 0; k < dealers.size(); k++) {
						JSONObject dealer = dealers.getJSONObject(k);
						// String[] _location = dealer.getString("_location").split(",");
						// 判断返回经销商是否为福特或福特进口
						if (!dealer.getString("JVFlag").contains("CAF")) {
							continue;
						}
						cityName = dealer.getString("_city");
						String name = dealer.getString("_name");
						if(dealerNames.contains(name)) {
							continue;
						} else {
							dealerNames.add(name);
						}
						String address = dealer.getString("_address");
						String[] loca = Location.getLocation(address);
						String lng = loca[0];
						String lat = loca[1];
						
						String serviceTell = dealer.getString("ServicePhoneNumber");

						String sellTell = dealer.getString("SalesPhoneNumber");

						List<String> shareholder = TianYanCha.getShareholder(name);
						String sControllingShareholder = shareholder.get(0);
						String sOtherShareholders = shareholder.get(1);

						AgencyEntity agency = new AgencyEntity();
						agency.setdCloseDate(null);
						agency.setdOpeningDate(null);
						agency.setdUpdateTime(new Timestamp(System.currentTimeMillis()));
						agency.setnBrandID(-1);
						agency.setsBrand("福特");
						agency.setnDealerIDWeb(-1);
						agency.setnManufacturerID(-1);
						agency.setsManufacturer("长安福特");
						agency.setnState(1);
						agency.setsAddress(address);
						agency.setsCity(cityName);
						agency.setsCustomerServiceCall(serviceTell);
						agency.setsDealerName(name);
						agency.setsDealerType(null);
						agency.setsProvince(proName);
						agency.setsSaleCall(sellTell);

						agency.setsLongitude(lng);
						agency.setsLatitude(lat);
						agency.setsControllingShareholder(sControllingShareholder);
						agency.setsOtherShareholders(sOtherShareholders);
						System.out.println(agency);
						list.add(agency);
						

					}

				}

			}

		}
		List<AgencyEntity> newList = distinct(list);
		return newList;
	}

	/**
	 * 对List去重
	 * 
	 * @param oldList
	 * @return
	 */
	List<AgencyEntity> distinct(List<AgencyEntity> oldList) {
		List<AgencyEntity> newList = new ArrayList<AgencyEntity>();
		for (AgencyEntity agency : oldList) {
			if (!newList.contains(agency)) {
				newList.add(agency);
			}
		}
		return newList;
	}

	public static void main(String[] args) {
		long start = System.currentTimeMillis();

		ChangAnFuTe crawler = new ChangAnFuTe();
		System.out.println("爬虫开始...");
		List<AgencyEntity> agencys = crawler.getAgency();
		System.out.println("抓取完毕,正在存库");
		for (AgencyEntity agency : agencys) {
	 		MybatisTool.save(agency);
		}
		MybatisTool.close();
		System.out.println("请查看数据库");
		long end = System.currentTimeMillis();
		System.out.println("运行时间:"+(end-start)/1000/60);
	}
}
